package com.niit.hbase.wordcount;

import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;

import java.io.IOException;

public class WordCountReduce extends TableReducer<Text, IntWritable, ImmutableBytesWritable> {

    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {

        //1.判断key是否为空，如果为空则跳过
        if(  key.toString().isEmpty()   ){
            return;
        }
        //2.定义单词出现的次数
        int sum = 0;
        //3.根据相同的key 对value进行累加
        for (IntWritable i : values){
            sum += i.get();
        }
        //4.构建put对象， key 作为 rowkey
        Put put = new Put(Bytes.toBytes(key.toString()));
        //5.添加 列族 列 列值
        put.addColumn( Bytes.toBytes("content"),  Bytes.toBytes("count"),   Bytes.toBytes(String.valueOf(sum))  );
        //6.写入Hbase
        context.write(  new ImmutableBytesWritable( Bytes.toBytes(   key.toString()   )  ) ,put );


    }
}
